package com.mgy.api.framework.core.swagger;

import com.mgy.api.framework.core.filter.ForwardFilter;
import com.mgy.api.framework.core.handler.ApiFrameworkProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.context.properties.ConfigurationProperties;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * swagger
 * http://127.0.0.1:8081/swagger-ui.html#/
 *
 * @author mgy
 * @date 2019.11.13
 */
@Configuration
@EnableSwagger2
@EnableConfigurationProperties(ApiFrameworkProperties.class)
@ConditionalOnExpression("${api.framework.swagger.enable:true}")
public class SwaggerAutoConfiguration {

    @Autowired
    private ApiFrameworkProperties properties;

    @Bean
    public Docket getDocket() {
        if (properties == null || properties.getSwagger() == null || properties.getSwagger().getDocket() == null) {
            throw new RuntimeException("api.framework.swagger配置不正确");
        }
        return properties.getSwagger().getDocket().build();
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        ForwardFilter forwardFilter = new ForwardFilter();
        forwardFilter.setProperties(properties);
        bean.setFilter(forwardFilter);
        bean.addUrlPatterns("/*");
        bean.setOrder(0);
        return bean;
    }
}
